<template>
  <div class="app-container purchasewarehouseorder">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-date-picker
        v-model="listQuery.startTime"
        type="datetime"
        style="width: 140px"
        class="filter-item"
        default-time="00:00:00"
        value-format="timestamp"
        placeholder="选择开始日期"
      />-
      <el-date-picker
        v-model="listQuery.endTime"
        type="datetime"
        style="width: 140px"
        class="filter-item"
        default-time="23:59:59"
        value-format="timestamp"
        placeholder="选择结束日期"
      />
      <el-input
        v-model="listQuery.warehouseOrderNo"
        clearable
        class="filter-item"
        style="width: 140px;"
        placeholder="输入单号"
      />
      <el-input
        v-model="listQuery.skuSearch"
        clearable
        class="filter-item"
        style="width: 160px;"
        placeholder="输入条码/商品名称"
      />
      <el-select
        v-model="listQuery.warehouseOrderState"
        clearable
        style="width: 120px"
        class="filter-item"
        placeholder="请选择状态"
      >
        <el-option
          v-for="(item, index) in statusMap"
          :key="index"
          :label="item.name"
          :value="item.value"
        />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button
        v-permission="['warehouse:purchasewarehouseorder:create']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-data-analysis"
        @click="skuSummary"
      >导出</el-button>
    </div>
    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      style="white-space: pre-line"
      height="300"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="warehouseOrderNo" align="center" label="单号" width="150px">
        <template slot-scope="scope">
          <el-link
            :underline="false"
            type="primary"
            @click="handleDetail(scope.row)"
          >{{ scope.row.warehouseOrderNo }}</el-link>
        </template>
      </el-table-column>
      <el-table-column align="center" label="入库时间" prop="warehouseOrderInsertTime">
        <template slot-scope="scope">
          <el-col>
            {{
              scope.row.warehouseOrderInsertTime | formatGmt
            }}
          </el-col>
        </template>
      </el-table-column>
      <el-table-column prop="warehouseOrderGoodsCount" align="center" label="入库数量" />
      <el-table-column prop="warehouseOrderGoodsAmount" align="center" label="入库金额">
        <template slot-scope="scope">
          {{
            (scope.row.warehouseOrderGoodsAmount / 100).toFixed(2)
          }}
        </template>
      </el-table-column>
      <el-table-column prop="supplierName" align="center" label="供应商" />
      <el-table-column prop="adminRealname" align="center" label="操作人" />
      <el-table-column prop="warehouseOrderConfirmRealname" align="center" label="确认人" />
      <el-table-column prop="warehouseOrderState" align="center" label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.warehouseOrderState === 0">待入库</el-tag>
          <el-tag v-if="scope.row.warehouseOrderState === 1">已入库</el-tag>
          <el-tag v-if="scope.row.warehouseOrderState === -1" type="danger">驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="操作"
        width="300"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            v-permission="['warehouse:purchasewarehouseorder:audit']"
            v-if="scope.row.warehouseOrderState == '0'"
            type="primary"
            size="mini"
            @click="handleAudit(scope.row)"
          >审批</el-button>
          <el-button
            v-permission="['warehouse:purchasewarehouseorder:update']"
            v-if="scope.row.warehouseOrderState != '1'"
            type="primary"
            size="mini"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>
          <el-button
            v-permission="['warehouse:purchasewarehouseorder:detail']"
            type="primary"
            size="mini"
            @click="handleDetail(scope.row)"
          >查看</el-button>
          <el-button type="primary" size="mini" @click="handlePrint(scope.row)">打印</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 审核对话框 -->
    <el-dialog v-loading="auditFormLoading" :visible.sync="auditDialogVisible" width="30%" center>
      <el-form ref="auditDataForm" :model="auditDataForm">
        <el-form-item align="center">
          <el-radio-group v-model="auditDataForm.warehouseOrderState">
            <el-radio label="1" @change="changeWarehouseOrderState">通过</el-radio>
            <el-radio label="-1" @change="changeWarehouseOrderState">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="auditDataForm.warehouseOrderState == '-1'" label="驳回理由">
          <el-input v-model="auditDataForm.auditComment" type="textarea" rows="3" placeholder />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="auditOrder()">确认</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 -->
    <el-dialog
      v-loading="optloading"
      :width="optDiaLogWidth"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="100px"
      >
        <el-form-item prop="warehouseId">
          <label slot="label">仓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;库</label>
          <el-select v-model="dataForm.warehouseId" placeholder="请选择" @change="ifCanSelSpu">
            <el-option
              v-for="(key, index) in warehouseList"
              :key="index"
              :label="key.warehouseName"
              :value="key.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="单据备注" prop="warehouseOrderInfo">
          <el-col :span="12">
            <el-input v-model="dataForm.warehouseOrderInfo" type="textarea" clearable placeholder />
          </el-col>
        </el-form-item>
        <el-form-item prop="supplierId">
          <label slot="label">供&nbsp;&nbsp;应&nbsp;&nbsp;商</label>
          <el-select v-model="dataForm.supplierId" placeholder="请选择">
            <el-option
              v-for="(key, index) in supplierList"
              :key="index"
              :label="key.supplierName"
              :value="key.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入库商品" prop="purchaseWarehouseOrderGoodsDOS">
          <el-col :span="4">
            <span>
              已选择({{
                selectSpuList.length > 0 ? selectSpuList.length : "0"
              }})件商品
            </span>
          </el-col>
          <el-col :span="10">
            <el-button
              :disabled="dataForm.warehouseIsSelected"
              type="primary"
              size="mini"
              @click="handleSpuAdd(dataForm.warehouseId)"
            >选择商品</el-button>
          </el-col>
        </el-form-item>
        <el-form-item label="商品详情" prop="purchaseWarehouseOrderGoodsDTOS">
          <el-table
            :data="selectSpuList"
            size="small"
            border
            fit
            highlight-current-row
            style="white-space: pre-line"
          >
            <el-table-column v-if="hidden" align="center" label="goodsId" prop="goodsId" />
            <el-table-column v-if="hidden" align="center" label="skuId" prop="skuId" />
            <el-table-column align="center" label="商品" prop="goodsName" width="180px">
              <template slot-scope="scope">
                <el-col :span="6">
                  <img :src="scope.row.img + '?x-oss-process=style/100px'" width="40" >
                </el-col>
                <el-col :span="18" style="padding-top: 15px;">
                  {{
                    scope.row.goodsName
                  }}
                </el-col>
              </template>
            </el-table-column>
            <el-table-column align="center" label="条形码" prop="barCode" />
            <el-table-column prop="unit" align="center" label="单位" width="60px" />
            <el-table-column align="center" label="入库数量" prop="warehouseGoodsBuyNum" width="100px">
              <template slot-scope="scope">
                <el-form ref="scope.row" :rules="spuNumFormRules" status-icon>
                  <el-form-item>
                    <el-input v-model="scope.row.warehouseGoodsBuyNum" placeholder />
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column align="center" label="入库总价" prop="warehouseGoodsAmount" width="120px">
              <template slot-scope="scope">
                <el-input v-model="scope.row.warehouseGoodsAmount" placeholder />
              </template>
            </el-table-column>
            <el-table-column align="center" label="入库单价" prop="warehouseGoodsPrice" width="120px">
              <template slot-scope="scope">
                <el-col
                  v-if="
                    scope.row.warehouseGoodsAmount &&
                      scope.row.warehouseGoodsBuyNum
                  "
                >
                  <span>
                    {{
                      Math.round(
                        (scope.row.warehouseGoodsAmount * 100) /
                          scope.row.warehouseGoodsBuyNum
                      ) / 100
                    }}
                  </span>
                </el-col>
              </template>
            </el-table-column>
            <!-- <el-table-column align="center" label="入库单价" prop="warehouseGoodsPrice" width="120px">
              <template slot-scope="scope">
                <el-form ref="scope.row" :rules="spuPriceFormRules">
                  <el-form-item prop="spuPrice">
                    <el-input v-model="scope.row.warehouseGoodsPrice" placeholder="" @blur="goodsPriceLimit(scope.row)" />
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column align="center" label="入库金额" prop="warehouseGoodsAmount">
              <template slot-scope="scope">
                <el-col v-if="scope.row.warehouseGoodsPrice && scope.row.warehouseGoodsBuyNum"><span>{{ (scope.row.warehouseGoodsPrice * scope.row.warehouseGoodsBuyNum).toFixed(2) }}</span></el-col>
              </template>
            </el-table-column>-->
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-link :underline="false" @click="removeSpu(scope.row.skuId)">
                  <span style="color: red;">移除</span>
                </el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="优惠金额" prop="warehouseOrderConpon">
          <el-col :span="6">
            <el-input v-model="dataForm.warehouseOrderConpon" clearable placeholder />
          </el-col>
        </el-form-item>
        <el-form-item label="入库时间" prop="warehouseOrderInsertTime">
          <el-date-picker
            v-model="dataForm.warehouseOrderInsertTime"
            type="datetime"
            style="width: 190px"
            class="filter-item"
            default-time="00:00:00"
            placeholder="选择入库时间"
          />
        </el-form-item>
        <el-form-item label="入库总额" prop="totalPrice">
          <span>{{ selSpuListTotalPrice }}</span>
        </el-form-item>
        <el-form-item label="入库总数" prop="total">
          <span>{{ selSpuListTotal }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus == 'create'" type="primary" @click="createData(0)">确认入库</el-button>
        <el-button v-else type="primary" @click="updateData(0)">确认入库</el-button>
      </div>
    </el-dialog>
    <!-- 添加商品 -->
    <el-dialog :visible.sync="spuDialogFormVisible" :custom-class="spuDialogClass" title="商品选择">
      <template>
        <div class="app-container" style="padding-bottom: 0;padding-top: 0;">
          <!-- 查询和其他操作 -->
          <div class="filter-container">
            <el-cascader
              :options="categoryOptions"
              :props="{ checkStrictly: true }"
              placeholder="请选择类目"
              clearable
              class="filter-item"
              filterable
              style="width: 200px;"
              @change="handleCategoryOption"
            />
            <el-input
              v-model="listSpuQuery.search"
              clearable
              class="filter-item"
              style="width: 200px;"
              placeholder="输入名称或条码"
            />
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              @click="handleSpuFilter"
            >查找</el-button>
          </div>

          <!-- 查询结果 -->
          <el-table
            v-loading="listSpuLoading"
            ref="spuTable"
            :data="spuList"
            :row-key="getRowKey"
            size="small"
            element-loading-text="正在查询中。。。"
            border
            fit
            highlight-current-row
            style="white-space: pre-line"
            max-height="400"
            @selection-change="selectChange"
          >
            <el-table-column :reserve-selection="true" align="center" type="selection" width="55" />
            <el-table-column v-if="hidden" prop="goodsId" align="center" label="goodsId" />
            <el-table-column v-if="hidden" prop="spuName" />
            <el-table-column v-if="hidden" prop="skuName" />
            <el-table-column v-if="hidden" prop="skuId" />
            <el-table-column v-if="hidden" prop="spuId" />
            <el-table-column prop="goodsName" align="center" label="商品名称" width="180px">
              <template slot-scope="scope">
                <el-col :span="6">
                  <img :src="scope.row.img + '?x-oss-process=style/100px'" width="40" >
                </el-col>
                <el-col :span="18" style="padding-top: 15px;">
                  {{
                    scope.row.goodsName
                  }}
                </el-col>
              </template>
            </el-table-column>
            <el-table-column prop="unit" align="center" label="单位" />
            <el-table-column prop="barCode" align="center" label="条形码" />
          </el-table>
          <pagination
            v-show="spuListTotal > 0"
            :total="spuListTotal"
            :page.sync="listSpuQuery.pageNo"
            :limit.sync="listSpuQuery.limit"
            :pager-count="5"
            layout="prev, pager, next"
            style="padding-bottom: 0;padding-top: 0;"
            @pagination="listGoods"
          />
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="spuDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="saveWarehouseSpu">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 打印 -->
    <el-dialog :visible.sync="dialogTableVisible" title="打印" class="printBox">
      <printHtml :outbound="1" :p-order-id="pOrderId" />
    </el-dialog>
  </div>
</template>

<style lang="scss">
.el-table .cell {
  white-space: pre-line;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
.el-form-item__label {
  padding-right: 0 !important;
}

.el-form :not(.is-required) > .el-form-item__label {
  padding-left: 10px;
}
.spuDialogClass .el-dialog__body {
  padding-bottom: 0;
  padding-top: 10px;
}
.spuDialogClass .el-dialog__footer {
  padding-top: 0;
}
</style>

<script>
import {
  active,
  audit,
  create,
  del,
  list,
  update
} from '@/api/purchasewarehouseorder'
import { formatDateAndTime } from '@/filters'
import { timestampToTime } from '@/utils/dateTimeUtil'
import { listWareHousesByPara, exportSkuSummary } from '@/api/warehouse'
import { listSuppliersByPara } from '@/api/supplier'
import {
  listWarehouseSkusByPara,
  querySkusByWarehouseId
} from '@/api/purchasewarehouseordergoods'
import { categorySecondLevelTree, categoryTree } from '@/api/category'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
const extraStatusMap = {
  '0': '待入库',
  '1': '已入库',
  '-1': '驳回'
}
export default {
  name: 'PurchaseWarehouseOrder',
  components: {
    Pagination
  },
  filters: {
    formatGmt(time) {
      if (time == null || time === '') {
        return ''
      }
      return formatDateAndTime(time)
    },
    formatOrderState(state) {
      switch (state) {
        case 0:
          return '待入库'
        case 1:
          return '已入库'
        case -1:
          return '驳回'
        default:
          return ''
      }
    }
  },
  data() {
    return {
      dialogTableVisible: false,
      pOrderId: '', // 844
      extraStatusMap,
      statusMap: [
        { value: 0, name: '待入库' },
        { value: 1, name: '已入库' },
        { value: -1, name: '驳回' }
      ],
      list: undefined,
      optloading: false,
      warehouseList: [],
      supplierList: [],
      spuList: [],
      selectSpuList: [],
      selectGoodList: [],
      categoryOptions: [],
      spuListTotal: 0,
      total: 0,
      listLoading: true,
      listSpuLoading: true,
      auditFormLoading: false,
      listQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined,
        gmtCreate: undefined,
        warehouseOrderNo: undefined,
        warehouseOrderState: undefined
      },
      hidden: false,
      listSpuQuery: {
        pageNo: 1,
        limit: 20,
        status: undefined,
        gmtCreate: undefined,
        warehouseOrderNo: undefined,
        warehouseId: undefined,
        search: '',
        categoryIds: '',
        categorySecondIds: '',
        warehouseOrderId: undefined
      },
      options: [],
      categoryList: [],
      categorySecondList: [],
      dataForm: {
        id: undefined,
        purchaseWarehouseOrderGoodsDTOS: [],
        warehouseOrderState: 0,
        totalPrice: 0,
        total: 0,
        warehouseId: undefined,
        warehouseIsSelected: true,
        warehouseOrderConpon: 0,
        supplierInfo: {},
        supplierName: undefined,
        supplierId: undefined
      },
      auditDataForm: {
        auditComment: '',
        warehouseOrderState: '1',
        warehouseOrderId: undefined
      },
      commentShow: false,
      dialogFormVisible: false,
      dialogStatus: '',
      auditDialogVisible: false,
      spuDialogFormVisible: false,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      spuNumFormRules: {
        spuNum: []
      },
      spuPriceFormRules: {
        spuPrice: []
      },
      rules: {
        warehouseId: [
          { required: true, message: '请选择仓库', trigger: 'blur' }
        ],
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'blur' }
        ],
        warehouseOrderInsertTime: [
          { required: true, message: '请选择入库时间', trigger: 'blur' }
        ],
        warehouseOrderConpon: [
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请核对格式(整数或者两位小数)',
            trigger: 'blur'
          }
        ]
      },
      optDiaLogWidth: '70%',
      spuDialogClass: 'spuDialogClass',
      goodNumValid: true,
      goodPriceValid: true
    }
  },
  computed: {
    selSpuListTotal: function() {
      if (this.selectSpuList.length) {
        let total = 0
        for (let i = 0; i < this.selectSpuList.length; i++) {
          if (
            this.selectSpuList[i].warehouseGoodsBuyNum &&
            new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(
              this.selectSpuList[i].warehouseGoodsBuyNum
            )
          ) {
            total += parseFloat(this.selectSpuList[i].warehouseGoodsBuyNum)
          }
        }
        return Math.round(total * 1000) / 1000
      }
    },
    selSpuListTotalPrice: function() {
      let totalPrice = 0
      for (let i = 0; i < this.selectSpuList.length; i++) {
        if (
          this.selectSpuList[i].warehouseGoodsAmount &&
          new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(
            this.selectSpuList[i].warehouseGoodsAmount
          )
        ) {
          totalPrice += parseFloat(this.selectSpuList[i].warehouseGoodsAmount)
        }
      }
      return Math.round(totalPrice * 100) / 100
    }
  },
  watch: {
    dialogFormVisible: {
      handler(newVal, objVal) {
        if (newVal === false) {
          if (this.$refs.spuTable) {
            this.$refs.spuTable.clearSelection()
          }
        }
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      list(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      if (this.listQuery.startTime && this.listQuery.startTime !== '') {
        var startTimeLong = this.listQuery.startTime
        this.listQuery.insertStartTime = timestampToTime(startTimeLong)
      }
      if (this.listQuery.endTime && this.listQuery.endTime !== '') {
        var endTimeLong = this.listQuery.endTime
        this.listQuery.insertEndTime = timestampToTime(endTimeLong)
      }
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSpuFilter() {
      this.listSpuQuery.pageNo = 1
      this.listGoods()
    },
    resetForm() {
      this.selectSpuList = []
      this.spuListTotal = 0
      this.supplierList = []
      this.dataForm = {
        id: undefined,
        purchaseWarehouseOrderGoodsDTOS: [],
        totalPrice: 0.0,
        total: 0,
        warehouseOrderConpon: 0,
        warehouseId: undefined,
        warehouseIsSelected: true,
        supplierInfo: undefined,
        supplierId: undefined
      }
      this.listSpuQuery = {
        pageNo: 1,
        limit: 20,
        status: undefined,
        gmtCreate: undefined,
        warehouseOrderNo: undefined,
        warehouseId: undefined,
        search: '',
        categoryIds: '',
        categorySecondIds: '',
        warehouseOrderId: undefined
      }
    },
    handleStatus(row) {
      this.resetForm()
      this.dataForm.id = row.id
      this.dataForm.status = row.status === 1 ? 0 : 1
      active(this.dataForm)
        .then(res => {
          this.$notify.success({
            title: '成功',
            message: '状态更改成功'
          })
          this.getList()
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    listWareHousesByPara() {
      listWareHousesByPara({ status: 1 })
        .then(response => {
          this.warehouseList = response.data.data
        })
        .catch(() => {
          this.warehouseList = []
        })
    },
    listSuppliersByPara() {
      this.listQuery.status = 1
      listSuppliersByPara(this.listQuery)
        .then(response => {
          this.supplierList = response.data.data
        })
        .catch(() => {
          this.supplierList = []
        })
    },
    handleCreate() {
      this.resetForm()
      this.listWareHousesByPara()
      this.listSuppliersByPara()
      this.dialogStatus = 'create'
      this.selectSpuList = []
      this.dialogFormVisible = true
      this.goodNumValid = true
      this.goodPriceValid = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(status) {
      if (this.$refs.spuTable) {
        this.$refs.spuTable.clearSelection()
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const selectSpuList = this.selectSpuList
          let isHasEmptyValue = false
          let isHasEmpValue = ''
          let goodNumValid = true
          let goodnumvalue = ''
          let goodPriceValid = true
          let goodValuePrice = ''
          for (let i = 0; i < selectSpuList.length; i++) {
            if (
              !selectSpuList[i].warehouseGoodsBuyNum ||
              !selectSpuList[i].warehouseGoodsAmount
            ) {
              isHasEmptyValue = true
              isHasEmpValue = selectSpuList[i].spuName
              break
            }
            if (
              !new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(
                selectSpuList[i].warehouseGoodsBuyNum
              )
            ) {
              goodNumValid = false
              goodnumvalue = selectSpuList[i].spuName
              break
            }
            if (
              !new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(
                selectSpuList[i].warehouseGoodsAmount
              )
            ) {
              goodPriceValid = false
              goodValuePrice = selectSpuList[i].spuName
              break
            }
            selectSpuList[i].warehouseGoodsPrice =
              Math.round(
                (selectSpuList[i].warehouseGoodsAmount * 100) /
                  selectSpuList[i].warehouseGoodsBuyNum
              ) / 100
          }
          if (selectSpuList.length === 0) {
            this.$notify.warning({
              title: '提示',
              message: '请选择入库商品'
            })
            return
          } else if (isHasEmptyValue) {
            this.$notify.warning({
              title: '提示',
              message: `请核对${isHasEmpValue}入库商品数量及总价`
            })
            return
          } else if (!goodNumValid) {
            this.$notify({
              title: '提示',
              message: `${goodnumvalue}入库数量请填写1到3位小数`,
              type: 'warning'
            })
            return
          } else if (!goodPriceValid) {
            this.$notify({
              title: '提示',
              dangerouslyUseHTMLString: true,
              message: `${goodValuePrice}入库总价核对格式<br>(整数或者两位小数)`,
              type: 'warning'
            })
          } else {
            this.dataForm.purchaseWarehouseOrderGoodsDTOS = this.selectSpuList
            this.dataForm.warehouseOrderState = status
            let supplierInfo = {}
            if (this.supplierList && this.supplierList.length > 0) {
              for (let i = 0; i < this.supplierList.length; i++) {
                if (this.supplierList[i].id === this.dataForm.supplierId) {
                  supplierInfo = this.supplierList[i]
                  break
                }
              }
            }
            if (supplierInfo) {
              this.dataForm.supplierName = supplierInfo.supplierName
              this.dataForm.supplierId = supplierInfo.id
              this.dataForm.supplierContacts = supplierInfo.supplierContacts
              this.dataForm.supplierPhone = supplierInfo.supplierPhone
            }
            this.dataForm.total = this.selSpuListTotal
            this.dataForm.totalPrice = this.selSpuListTotalPrice
            this.optloading = true
            create(this.dataForm)
              .then(response => {
                this.optloading = false
                this.getList()
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '创建成功'
                })
              })
              .catch(response => {
                this.optloading = false
                this.$notify.error({
                  title: '失败',
                  message: '失败'
                })
              })
          }
        }
      })
    },
    handleUpdate(row) {
      this.listWareHousesByPara()
      this.listSuppliersByPara()
      this.listSpuQuery.warehouseOrderId = row.id
      this.listWarehouseGoods()
      this.dataForm = Object.assign({}, row)
      const conpon = this.dataForm.warehouseOrderConpon
        ? (this.dataForm.warehouseOrderConpon / 100).toFixed(2)
        : ''
      this.$set(this.dataForm, 'warehouseOrderConpon', conpon)
      this.dataForm.supplierId = row.supplierId
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.goodNumValid = true
      this.goodPriceValid = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAudit(row) {
      this.auditDialogVisible = true
      this.auditDataForm = {
        auditComment: '',
        warehouseOrderState: '1',
        warehouseOrderId: row.id
      }
    },
    auditOrder() {
      if (this.auditDataForm.warehouseOrderState === '-1') {
        if (
          this.auditDataForm.auditComment === '' ||
          this.auditDataForm.auditComment.trim() === ''
        ) {
          this.$notify.error({
            title: '失败',
            message: '请填写驳回意见'
          })
          return
        }
      }
      this.auditFormLoading = true
      audit(this.auditDataForm)
        .then(response => {
          this.auditFormLoading = false
          this.auditDialogVisible = false
          this.$notify.success({
            title: '成功',
            message: '审核成功'
          })
          this.getList()
        })
        .catch(response => {
          this.auditFormLoading = false
          this.$notify.error({
            title: '失败',
            message: '失败'
          })
        })
    },
    updateData(status) {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const selectSpuList = this.selectSpuList
          let isHasEmptyValue = false
          let isHasEmpValue = ''
          let goodNumValid = true
          let goodnumvalue = ''
          let goodPriceValid = true
          let goodValuePrice = ''
          for (let i = 0; i < selectSpuList.length; i++) {
            if (
              !selectSpuList[i].warehouseGoodsBuyNum ||
              !selectSpuList[i].warehouseGoodsAmount
            ) {
              isHasEmptyValue = true
              console.log(selectSpuList[i].spuName, '老师的看法就')
              isHasEmpValue = selectSpuList[i].spuName
              break
            }
            if (
              !new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(
                selectSpuList[i].warehouseGoodsBuyNum
              )
            ) {
              goodNumValid = false
              goodnumvalue = selectSpuList[i].spuName
              break
            }
            if (
              !new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(
                selectSpuList[i].warehouseGoodsAmount
              )
            ) {
              goodPriceValid = false
              goodValuePrice = selectSpuList[i].spuName
              break
            }
            selectSpuList[i].warehouseGoodsPrice =
              Math.round(
                (selectSpuList[i].warehouseGoodsAmount * 100) /
                  selectSpuList[i].warehouseGoodsBuyNum
              ) / 100
          }
          if (selectSpuList.length === 0) {
            this.$notify.error({
              title: '失败',
              message: '请选择入库商品'
            })
            return
          } else if (isHasEmptyValue) {
            this.$notify.error({
              title: '失败',
              message: `请核对${isHasEmpValue}入库商品数量及单价`
            })
            return
          } else if (!goodNumValid) {
            this.$notify({
              title: '提示',
              message: `${goodnumvalue}入库数量请填写1到3位小数`,
              type: 'warning'
            })
          } else if (!goodPriceValid) {
            this.$notify({
              title: '提示',
              dangerouslyUseHTMLString: true,
              message: `${goodValuePrice}入库单价核对格式<br>(整数或者两位小数)`,
              type: 'warning'
            })
            return
          } else {
            this.dataForm.purchaseWarehouseOrderGoodsDTOS = this.selectSpuList
            this.dataForm.warehouseOrderState = status
            let supplierInfo = {}
            if (this.supplierList && this.supplierList.length > 0) {
              for (let i = 0; i < this.supplierList.length; i++) {
                if (this.supplierList[i].id === this.dataForm.supplierId) {
                  supplierInfo = this.supplierList[i]
                  break
                }
              }
            }
            if (supplierInfo) {
              this.dataForm.supplierName = supplierInfo.supplierName
              this.dataForm.supplierContacts = supplierInfo.supplierContacts
              this.dataForm.supplierPhone = supplierInfo.supplierPhone
            }
            this.dataForm.total = this.selSpuListTotal
            this.dataForm.totalPrice = this.selSpuListTotalPrice
            update(this.dataForm)
              .then(response => {
                this.getList()
                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '更新成功'
                })
              })
              .catch(response => {
                this.$notify.error({
                  title: '失败',
                  message: '失败'
                })
              })
          }
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(row)
            .then(response => {
              this.$notify.success({
                title: '成功',
                message: '删除成功'
              })
              const index = this.list.indexOf(row)
              this.list.splice(index, 1)
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: '失败'
              })
            })
        })
        .catch(() => {
          return false
        })
    },
    handleSpuAdd(warehouseId) {
      this.spuDialogFormVisible = true
      this.listSpuQuery.warehouseId = warehouseId
      this.categoryOptions = []
      this.categorySecondLevelTree()
      this.refreshCategoryOptions()
      this.listGoods()
    },
    listWarehouseGoods() {
      this.listSpuQuery.status = 1
      listWarehouseSkusByPara(this.listSpuQuery)
        .then(response => {
          this.selectSpuList = response.data.data
        })
        .catch(() => {
          this.selectSpuList = []
        })
    },
    listGoods() {
      this.listSpuQuery.status = 1
      this.listSpuLoading = true
      querySkusByWarehouseId(this.listSpuQuery)
        .then(response => {
          this.spuList = response.data.data.items
          this.spuListTotal = response.data.data.total
          this.listSpuLoading = false
          this.selectSpuList.forEach(row => {
            this.$refs.spuTable.toggleRowSelection(row, true)
          })
        })
        .catch(() => {
          this.spuList = []
          this.listSpuLoading = false
        })
    },
    ifCanSelSpu() {
      this.dataForm.warehouseIsSelected = true
      if (this.dataForm.warehouseId) {
        this.dataForm.warehouseIsSelected = false
      }
    },
    saveWarehouseSpu() {
      const selection = this.selectGoodList
      console.log(selection, '哈哈哈', this.selectSpuList)
      for (let i = 0; i < this.selectSpuList.length; i++) {
        for (let j = 0; j < selection.length; j++) {
          if (
            this.selectSpuList[i].skuId &&
            this.selectSpuList[i].skuId === selection[j].skuId &&
            (this.selectSpuList[i].warehouseGoodsBuyNum ||
              this.selectSpuList[i].warehouseGoodsAmount)
          ) {
            this.$set(
              selection[j],
              'warehouseGoodsBuyNum',
              this.selectSpuList[i].warehouseGoodsBuyNum
            )
            this.$set(
              selection[j],
              'warehouseGoodsAmount',
              this.selectSpuList[i].warehouseGoodsAmount
            )
            break
          }
        }
      }
      const selNewArr = this.unique(selection.concat(this.selectSpuList))
      console.log(this.unique(selection.concat(this.selectSpuList)))
      this.spuDialogFormVisible = false
      this.selectSpuList = selNewArr
    },
    unique(arr1) {
      const res = new Map()
      return arr1.filter(a => !res.has(a.skuId) && res.set(a.skuId, 1))
    },
    removeSpu(skuId) {
      for (let i = 0; i < this.selectSpuList.length; i++) {
        if (this.selectSpuList[i].skuId === skuId) {
          this.selectSpuList.splice(i, 1)
          break
        }
      }
      if (this.selectSpuList) {
        this.selectSpuList.forEach(row => {
          this.$refs.spuTable.toggleRowSelection(row)
        })
      }
    },
    categorySecondLevelTree() {
      categorySecondLevelTree()
        .then(response => {
          this.categoryList = response.data.data
        })
        .catch(() => {
          this.categoryList = []
        })
    },
    handleCategoryOption(e) {
      if (e !== undefined) {
        const tag = e[e.length - 1]
        this.listSpuQuery.skuIds = tag // 回调指定分类
      } else {
        this.listSpuQuery.skuIds = undefined
      }
    },
    refreshCategoryOptions() {
      if (this.categoryOptions.length === 0) {
        categoryTree().then(response => {
          this.categoryOptions = response.data.data.map(item => {
            item.children.length == 0 ? delete item.children : ''
            return item
          })
        })
      }
    },
    changeWarehouseOrderState() {
      const comment = this.auditDataForm.auditComment
      this.auditDataForm.auditComment =
        this.auditDataForm.warehouseOrderState === '1' ? '' : comment
    },
    handleDetail(row) {
      this.$router.push({ path: '/warehouse/order_detail?pOrderId=' + row.id })
    },
    handlePrint(row) {
      // var url = window.location.href.split('#')[0]
      // window.open(`${url}#/printdetail?pOrderId=${row.id}&outbound=1`)
      this.dialogTableVisible = true
      this.pOrderId = row.id
    },
    getRowKey(row) {
      return row.skuId
    },
    selectChange(selection) {
      this.selectGoodList = selection
    },
    goodsBuyNumLimit(row) {
      const flag = new RegExp('^[0-9]+(.[0-9]{1,3})?$').test(
        row.warehouseGoodsBuyNum
      )
      if (!flag) {
        this.goodNumValid = false
      } else {
        this.goodNumValid = true
      }
    },
    goodsPriceLimit(row) {
      const flag = new RegExp('^[0-9]+(.[0-9]{1,2})?$').test(
        row.warehouseGoodsPrice
      )
      if (!flag) {
        this.goodPriceValid = false
      } else {
        this.goodPriceValid = true
      }
    },
    skuSummary() {
      let startTime = ''
      let endTime = ''
      // debugger
      if (
        (!this.listQuery.startTime || !this.listQuery.startTime) &&
        !this.pwOrderIdStr
      ) {
        this.$notify.info({
          title: '系统提示',
          message: '请选择导出时间范围'
        })
        return
      }
      if (this.listQuery.startTime && this.listQuery.startTime !== '') {
        var startTimeLong = this.listQuery.startTime
        startTime = timestampToTime(startTimeLong)
      }
      if (this.listQuery.endTime && this.listQuery.endTime !== '') {
        var endTimeLong = this.listQuery.endTime
        endTime = timestampToTime(endTimeLong)
      }
      exportSkuSummary(
        startTime,
        endTime,
        0,
        this.listQuery.warehouseOrderState,
        extraStatusMap[this.listQuery.warehouseOrderState],
        this.listQuery.warehouseOrderNo,
        11,
        this.listQuery.skuSearch,
        this.pwOrderIdStr
      )
    },
    handleSelectionChange(val) {
      console.log(val)
      var arr = []
      val.forEach(v => {
        arr.push(v.id)
      })
      this.pwOrderIdStr = arr.join(',') + ','
      console.log(this.pwOrderIdStr)
    }
  }
}
</script>
